package com.zzp.zjs_bos.shiro;

import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.zzp.zjs_bos.dao.IFunctionDao;
import com.zzp.zjs_bos.dao.IUserDao;
import com.zzp.zjs_bos.domain.Function;
import com.zzp.zjs_bos.domain.User;
import com.zzp.zjs_bos.utils.MD5Utils;

/*自定义Realm,实现授权和认证操作*/
public class BOSRealm extends AuthorizingRealm{
	
	@Resource
	private IUserDao  userDao;
	
	@Resource
	protected IFunctionDao functionDao;
	
	//用于授权
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//授权信息对象
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//获取当前用户
		User user = (User) principals.getPrimaryPrincipal();
		if("admin".equals(user.getUsername())){
			List<Function> functions = functionDao.findAll();
			for (Function function : functions) {
				info.addStringPermission(function.getCode());
			}
		}else{
			List<Function> list = functionDao.findByUserId(user.getId());
			for (Function function : list) {
				info.addStringPermission(function.getCode());
			}
		}
		return info;
	}

	
	
	
	
	
	//用于认证
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken myToken = (UsernamePasswordToken)token; 
		String username = myToken.getUsername();
		//将用户名所对应的用户查出来，用户来自输入的用户名
		User user = userDao.findByUserName(username);
		if(user == null){
			return null;
		}
		
		// 参数一：签名对象，认证通过后，可以在程序的任意位置获取当前放入的对象
		// 参数二：数据库中查询出的密码
		// 参数三：当前realm的类名
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getSimpleName());
		return info;	
	}

}
